/**
 * Created by yangxin on 2016/11/29.
 */
import UAParser from 'ua-parser-js' // 客户端浏览器信息解析模块
import CryptoJS from "crypto-js"    // 加密模块
import * as constants from '../AppConstants'
import Moment from 'moment'
import cache from 'commons/cache'

/**
 * API接口参数签名
 * @param  {[Object]} reqParams [请求参数]
 * @return {[String]}           [参数签名字符串]
 */
const getSign = function (params) {
    if (!params) {
        throw new Error("无效的参数，签名失败")
    }
    let paramMap = new Map()
    for (let key in params) {
        if (key == constants.PARAM_SIGN_NAME) {
            continue
        }
        let value = params[key]
        if (value == null || value == undefine) {
            value = ''
            params[key] = ''
        }
        paramMap.set(key, value)
    }

    if (paramMap.size < 1) {
        return null
    }

    let str = ''

    // 1、排序
    let orderParamMap = new Map([...paramMap.entries()].sort())
    // 2、用&符号拼接
    for (let [key, value] of orderParamMap) {
        str += `${key}=${value}&`
    }
    str += constants.SIGN_SECURITY_KEY	// 最后拼接加密密钥
    // 3、签名
    let sign = CryptoJS.MD5(str).toString()
    return sign
}

const buildFormData = function (params) {
    let formData = new FormData()
    if (typeof params == 'object' && params) {
        Object.keys(params).forEach((k) => {
            formData.append(k, params[k]);
        })
    }
    return formData
}

const formDataToObject = function (formData, excludeFile) {
    if (!(formData instanceof FormData)) {
        return null
    }
    let obj = {}
    for (let entrie of formData.entries()) {
        let key = entrie[0]
        let value = entrie[1]
        if (excludeFile && value instanceof File) {
            continue
        }
        obj[key] = value
    }
    return obj
}

// 获取当前客户端所处的渠道
const getChannel = function () {
    if (isWeChat()) {
        return '1'  // 微信
    } else {
        return '5'  // H5/PC
    }
}

/**
 * 当前浏览器是否微信客户端
 * @returns {boolean} 微信客户端返回true，否则返回false
 */
const isWeChat = function () {
    let ua = UAParser(navigator.userAgent)
    let browserName = ua.browser.name
    return browserName == 'WeChat'
}

/**
 * 格式化日期
 * @param value     日期毫秒值
 * @param format    格式
 * @returns {string}
 */
const formatDate = function (value, format) {
    if (!value) {
        return ''
    }

    format = format || 'YYYY-MM-DD hh:mm:ss'
    return Moment(Number(value)).format(format)
}

const getNameByCode = function (arr, code, _props) {
    if (!Array.isArray(arr)) {
        return code
    }
    let props = Object.assign({
        code: 'code',
        name: 'name'
    }, _props)
    let filter =  arr.filter((item) => item[props.code] == code)
    return filter.length == 0?(props.emptyText||''):filter[0][props.name]
}

const isUserSelf = function (uid) {
    return JSON.parse(cache.getValue(constants.CACHE_USER_INFO) || '{}').id == uid
}

const isDisabeldStates = function (states, disabledStates) {
    return (disabledStates || constants.STATUS_DISABLED) == states
}

const title = function (title) {
    let t = title ? `${constants.APP_TITLE} - ${title}` : constants.APP_TITLE;
    window.document.title = t;
}

/**
 * 是否登录
 */
const isLogin = function () {
    let apiToken = cache.getValue(constants.CACHE_API_TOKEN)
    let userInfo = cache.getValue(constants.CACHE_USER_INFO)
    return apiToken && apiToken.length === 36 && userInfo != null
}

/**
 * 根据身份证号计算年龄
 * @param idcard
 * @return {*}
 */
const calcAge = function (idcard) {
    if (!idcard) {
        return ''
    }
    if (idcard.length != 18) {
        return idcard
    }
    let birthdayYear = idcard.substr(6,4)
    let currYear = new Date().getFullYear()
    let age = currYear - birthdayYear
    return age
}

const getHrefParamerer = function(name){
    let href = window.location.href
    if(href.indexOf("?") == -1){
        return ''
    }
    let params = href.substring(href.indexOf('?') + 1).split('&');
    let value = ''
    params.forEach(param => {
        let kv = param.split('=')
        if(kv[0] == name){
            value = kv[1]
        }
        return false
    })
    return value
}

const getLastPath = function(path){
    let href = path || window.location.href
    if(href.indexOf("?") != -1){
        href = href.substring(0, href.indexOf("?"))
    }
    let paths = href.split('/')
    if(paths.length > 0){
        return paths[paths.length-1]
    }
    return ''
}

export default {
    isWeChat,
    getSign,
    getChannel,
    formatDate,
    title,
    getNameByCode,
    isUserSelf,
    isDisabeldStates,
    calcAge,
    isLogin,
    buildFormData,
    formDataToObject,
    getHrefParamerer,
    getLastPath
}
